// components/detailShare/detailShare.js
import api from '../../utils/api'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    detailData: {
      type: Object,
      value: {}
    },
    type: {
      type: Number,
      value: 1
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    shareList: [
      {
        image: "../../assets/image/detail/wechat.png",
        text: '分享给好友',
        id: 'wechat',
        shareType: 'share'
      },
      {
        image: "../../assets/image/detail/playbill.png",
        text: '生成海报',
        id: 'playbill',
        shareType: 'playbill'
      }
      // {
      //   image: "../../assets/image/detail/moments.png",
      //   text: '分享到朋友圈',
      //   id: 'moments',
      //   shareType: ''
      // },
 
    ],
    showCanvas: false,
    cardBase: {
      //需要https图片路径,下载到本地然后去绘制
      cardbg: "https://7265-redux-32ab9a-1259022487.tcb.qcloud.la/image/222.jpg",
      // 二维码
      codeImg: "https://7265-redux-32ab9a-1259022487.tcb.qcloud.la/image/111.png",
    },
    canvasMes: {},
    canvas: null,
    isAuthSavePhoto: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onShow() {
      this.setData({
        showCanvas: false
      })
    },
    cancelDiaglog() {
      this.triggerEvent("cancelShare")
    },
    shareMes(e) {
      let type = e.currentTarget.dataset.type
      if (type === 'wechat') {
        return
      }
      // this.triggerEvent("shareMes", {type: type})
      if (type === 'playbill') {
        let scene = ''
        if (this.properties.type * 1 === 1) {
          scene = `type=${this.properties.type}&productMirrorId=${this.properties.detailData.productMirrorId}`
        }
        if (this.properties.type * 1 === 2) {
          scene = `type=${this.properties.type}&productId=${this.properties.detailData.productId}`
        }
        api.getwxacode({
          data: {
            appid: 'wxff3fc00494f4f0e3',
            scene: scene,
            page: 'pages/detail/detail',
            width: 200
          },
          success: res => {
            if (res.code * 1 === 0) {
              let imgUrl = res.data.image
              this.createSelector(imgUrl)
              this.setData({
                showCanvas: true
              })
            }
          }
        })
      }
    },
    createSelector(imgUrl) {
      const query = this.createSelectorQuery()
      query.select('#myCanvas')
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')

          const dpr = wx.getSystemInfoSync().pixelRatio
          canvas.width = res[0].width * dpr
          canvas.height = res[0].height * dpr
          this.setData({
            canvasMes: {
              width: res[0].width * dpr,
              height: res[0].height * dpr
            },
            canvas: canvas
          })

          ctx.scale(dpr, dpr)

          let publicWidth = res[0].width
          let publicHeight = res[0].height

          // 创建背景
          ctx.fillStyle = "white"
          ctx.fillRect(0, 0, publicWidth, publicWidth + 180)

          // // 商品图
          let imgData = canvas.createImage()

          wx.getImageInfo({
            src: this.properties.detailData.coverImage,
            success(res) {
              imgData.src = res.path
              imgData.onload = function () {
                ctx.drawImage(imgData, 20, 10, publicWidth - 40, publicWidth - 40)
              }
            }
          })

          ctx.font = '10px sans-serif'
          ctx.fillStyle = "#333333"
          // 标题
          let text = this.properties.detailData.name
          let stringLen = text.split('').length
          if (stringLen <= 18) {
            ctx.fillText(this.properties.detailData.name, 20, 325, 200)
          } else {
            let lineNum = Math.ceil(stringLen / 18)
            for (let i = 0; i < lineNum; i++) {
              let line = ''
              for (let j = 0 ; j < 18 ; j++) {
                if (text.split('')[i * 18 + j]) {
                  line = line + text.split('')[i * 18 + j]
                }
              }
              ctx.fillText(line, 20, publicWidth + (i * 12), 200)
            }
          }

          let imgDataSec = canvas.createImage()
          //二维码
          wx.getImageInfo({
            src: imgUrl,
            success(res) {
              imgDataSec.src = res.path
              imgDataSec.onload = function () {
                ctx.drawImage(imgDataSec, 20, publicWidth + 40, 60, 60)
              }
            }
          })
          
          // 微信图片
          let imgDataTir = canvas.createImage()
          wx.getImageInfo({
            src: '../../assets/image/detail/wechat_logo.png',
            success(res) {
              imgDataTir.src = '/' + res.path
              imgDataTir.onload = function () {
                ctx.drawImage(imgDataTir, publicWidth - 80, publicWidth + 40, 60, 60)
              }
            }
          })

          ctx.font = '20px sans-serif'
          ctx.fillStyle = "#E11F5E"
          ctx.fillText('¥' + this.properties.detailData.payPrice, publicWidth - 80, publicWidth + 10, publicWidth)

          ctx.font = '10px sans-serif'
          ctx.fillStyle = "#999999"
          ctx.fillText('1.保存图片到相册', 95, publicWidth + 65, 200)

          ctx.font = '10px sans-serif'
          ctx.fillStyle = "#999999"
          ctx.fillText('2.打开微信扫码或长按识别', 95, publicWidth + 85, 200)
        })
    },
    saveImg() {
      let that = this
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.data.canvas.width,
        height: this.data.canvas.height,
        destWidth: this.data.canvas.width,
        destHeight: this.data.canvas.height,
        canvas: this.data.canvas,
        success(imgUrl) {
          that.getSetting().then((res) => {
            // 判断用户是否授权了保存到本地的权限
            if (!res.authSetting['scope.writePhotosAlbum']) {
              that.authorize().then(() => {
                that.savedownloadFile(imgUrl)

                that.setData({
                  isAuthSavePhoto: false
                })
              }).catch(() => {
                wx.showToast({
                  title: '您拒绝了授权',
                  icon: 'none',
                  duration: 1500
                })
                that.setData({
                  isAuthSavePhoto: true
                })
              })
            } else {

              that.savedownloadFile(imgUrl)

            }
          })
        }
      })
    },

    //打开设置，引导用户授权
    onOpenSetting() {
      wx.openSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.showToast({
              title: '您未授权',
              icon: 'none',
              duration: 1500
            })
            this.setData({ // 拒绝授权
              isAuthSavePhoto: true
            })

          } else { // 接受授权
            this.setData({
              isAuthSavePhoto: false
            })
            this.onSaveToPhone() // 接受授权后保存图片
          }

        }
      })

    },
    // 获取用户已经授予了哪些权限
    getSetting() {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: res => {
            resolve(res)
          }
        })
      })
    },
    // 发起首次授权请求
    authorize() {
      return new Promise((resolve, reject) => {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            resolve()
          },
          fail: res => { //这里是用户拒绝授权后的回调
            reject()
          }
        })
      })
    },
    savedownloadFile(img) {
      // this.downLoadFile(img).then((res) => {
      return this.saveImageToPhotosAlbum(img.tempFilePath)
      // }).then(() => {})
    },
    //单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
    downLoadFile(img) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: img,
          success: (res) => {
            resolve(res)
          }
        })
      })
    },
    // 保存图片到系统相册
    saveImageToPhotosAlbum(saveUrl) {
      return new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
          filePath: saveUrl,
          success: (res) => {
            wx.showToast({
              title: '保存成功,请去手机相册浏览',
              duration: 1000,
            })
            resolve()
          }
        })
      })
    },
    // 弹出模态框提示用户是否要去设置页授权
    showModal() {
      wx.showModal({
        title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
        success: (res) => {
          if (res.confirm) {
            this.onOpenSetting() // 打开设置页面          
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }
})